const path = require('path');
const Koa = require('koa');
const { requireAll } = require('../helpers/file');

function createApp() {
    const rawApp = new Koa();
    const app = {
        rawApp,
        use: (plugin) => {
            plugin.install(rawApp);
            return app;
        },
        listen: (port, callback) => rawApp.listen(port, callback),
    };
    return app;
}

function createApis(config) {
    config = Object.assign({
        dirname: path.resolve(),
        fileFilter: () => true,
    }, config);
    return {
        install(app) {
            const apis = requireAll(config);
            const apiMap = {};
            apis.forEach(api => {
                const { method, path, handler } = api;
                if (!apiMap[path]) {
                    apiMap[path] = {};
                }
                apiMap[path][method.toUpperCase()] = handler;
            });
            console.log(apiMap);
            app.use(ctx => {
                const { method, path } = ctx.request;
                console.log(method, path);
                if (apiMap[path] && apiMap[path][method]) {
                    ctx.body = apiMap[path][method]();
                } else {
                    ctx.status = 404;
                    ctx.body = 'Not Found.';
                }
            });
        },
    };
}

function defineApi(options) {
    return options;
}

module.exports = {
    createApp,
    createApis,
    defineApi,
};
